from django.shortcuts import render
from rest_framework.permissions import IsAuthenticated
from department.models import DoctorModel
from rest_framework.views import APIView
from rest_framework.response import Response
from .models import OrderModel,QuestionModel,QImageModel
import datetime,random
from django_redis import get_redis_connection
from django.db import transaction
from human.models import UserModel
from department.models import DoctorModel
from pdata.models import PListModel
from coupon.models import CouponLogModel
from .serial import OrderSerializer
import os
from django.conf import settings
from .server import get_pay_order

# Create your views here.

class DoctorView(APIView):

    def get(self, request):
        id = request.query_params.get('id')
        doctor = DoctorModel.objects.get(id=id)
        name = doctor.name
        department = doctor.department.name
        hospital = doctor.hospital.name
        price = doctor.price
        data = {
            'name': name,
            'department': department,
            'hospital': hospital,
            'price': price
        }
        return Response({'msg':data})


def count_price(user_id,coupon_id,price):
    coupon_redis = get_redis_connection('coupon')
    coupon_key = f"{user_id}:{coupon_id}"
    use_status = coupon_redis.hget(coupon_key, 'use_status').decode()
    if use_status == "0":
        discount = coupon_redis.hget(coupon_key, 'condition').decode()
        print(discount)
        if int(discount) > price:
            return False
        else:
            sale = coupon_redis.hget(coupon_key, 'sale').decode()
            print(sale)
            if sale[0] == "-":
                pay_price = price - int(sale[1:])
            else:
                pay_price = price * float(sale[1:])
            # 更新use_status为"1"，表示优惠券已使用
            coupon_redis.hset(coupon_key, 'use_status', '1')
            return pay_price
    else:
        return False


def save_image(image_list,order_id,qu):
    order_images = "pdata/" + datetime.datetime.now().strftime('%Y/%m/%d')
    save_dir = os.path.join(settings.MEDIA_ROOT, order_images)
    if not os.path.exists(save_dir):
        os.makedirs(save_dir)
    for index,image in enumerate(image_list):
        safe_filename = ''.join(x for x in image.name if x.isalnum() or x in "._- ")
        filename = f"{order_id}_{index}_{safe_filename}"
        file_path = os.path.join(save_dir, filename)
        # 使用Django的默认存储系统来保存文件
        # 如果您不想使用Django的存储系统，也可以使用标准的Python文件操作
        with open(file_path, 'wb+') as destination:
            for chunk in image.chunks():
                destination.write(chunk)

        QImageModel.objects.create(
                question=qu,
                image_path=os.path.join(order_images, filename)
        )

        print(f"保存成功")







class OrderView(APIView):
    permission_classes = [IsAuthenticated]

    def post(self, request):
        user_id = request.user.id
        doctor_id = request.data.get('doctor_id',None)
        patient_id = request.data.get('patient_id',None)
        image_list = request.FILES.getlist('image_list[]',None)
        content = request.data.get('content',None)
        coupon_id = request.data.get('coupon_id',None)
        open_status = request.data.get('open',None)
        print(image_list)
        reddis = get_redis_connection('order')
        cursor = '0'
        while cursor != 0:
            cursor, keys = reddis.scan(cursor=cursor, match=f"*{user_id}*")
            for key in keys:
                pay_status = reddis.hget(key, 'pay_status').decode()
                if pay_status == "0" or pay_status == "1":
                    return Response({'msg':'请先支付之前的订单或完成之前的订单'})

        # 生成时间戳部分
        timestamp = datetime.datetime.now().strftime('%Y%m%d%H%M%S')
        #  生成一个四位数的随机数
        random_num = "{0:04d}".format(random.randint(0, 9999))
        #  拼接成订单号
        order_id = f"{timestamp}{random_num}{user_id}{doctor_id}{patient_id}"
        # save_image(image_list,order_id)

        # 保存订单
        with transaction.atomic():
            savepoint = transaction.savepoint()
            try:
                # 查询优惠卷是否可用
                price = DoctorModel.objects.get(id=doctor_id).price
                if coupon_id is not None:
                    pay_price = count_price(user_id, coupon_id, price)
                    if pay_price is False:
                        return Response({'msg': '优惠券不可用'})
                else:
                    pay_price = price
                data = {
                    "user": UserModel.objects.get(id=user_id),
                    "doctor": DoctorModel.objects.get(id=doctor_id),
                    "patient": PListModel.objects.get(id=patient_id),
                    'pay_status':0,
                    'order_id':order_id,
                    'price':price,
                    'pay_price':pay_price,
                    'open_status':open_status,
                }
                if coupon_id is not None:
                    data['coupon'] = CouponLogModel.objects.get(id=coupon_id)
                order = OrderModel.objects.create(**data)
                print(order)
                redis_conn = get_redis_connection('order')
                pipe = redis_conn.pipeline()
                pipe.multi()
                redis_data = {
                    'user_id': order.user.id,
                    'doctor_id': order.doctor.id,
                    'patient_id': order.patient.id,
                    'order_id': order.order_id,
                    'price': order.price,
                    'pay_price': order.pay_price,
                    'open_status': order.open_status,
                    'create_time': order.create_time.strftime("%Y-%m-%d %H:%M:%S"),
                    'pay_status': order.pay_status,
                    'coupon_id': order.coupon.id if order.coupon is not None else '',
                    'pay_time': '',
                    'order': order.id,
                }
                pipe.hset(f"{order.user.id}:{order.order_id}",mapping=redis_data)
                print(f"{order.user.id}:{order.order_id}")
                pipe.execute()

                qu = QuestionModel.objects.create(
                    write=content,
                    order=order
                )
                save_image(image_list,order_id,qu)
            except Exception as e:
                transaction.savepoint_rollback(savepoint)
                redis_conn.delete(f"{order.user.id}:{order.order_id}")
                raise e
        return Response({'msg':"订单创建成功"})







class GetOrderView(APIView):
    permission_classes = [IsAuthenticated]

    def get(self,request):
        user_id = request.user.id
        res = get_pay_order(user_id)
        return Response({'msg':res})
